package com.zh.media.service;

import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;


import com.zh.media.https.MqttManager;
import com.zh.media.ui.MainActivity;

import org.apache.log4j.Logger;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class DownloadService extends IntentService {
    // 8 ~ 32k
    private static final int BUFFER_SIZE = 10 * 1024;
    private static final String TAG = "DownloadService";
    private static final String DOWNLOAD_URL = "DownloadService";

    //订阅主题
    private String mainTopic = "test";

    private static final int NOTIFICATION_ID = 0;

    private NotificationManager mNotifyManager;
    private NotificationCompat.Builder mBuilder;
    //log
    private static final Logger logger = Logger.getLogger(DownloadService.class);

    public DownloadService() {
        super("DownloadService");
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    protected void onHandleIntent(Intent intent) {
        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this);

        String appName = getString(getApplicationInfo().labelRes);
        int icon = getApplicationInfo().icon;

        mBuilder.setContentTitle(appName).setSmallIcon(icon);
        String urlStr = intent.getStringExtra(DOWNLOAD_URL);
        InputStream in = null;
        FileOutputStream out = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(false);
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.setReadTimeout(10 * 1000);
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("Charset", "UTF-8");
            urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");

            urlConnection.connect();
            long byteTotal = urlConnection.getContentLength();
            long byteSum = 0;
            int byteRead = 0;
            in = urlConnection.getInputStream();
            File dir = getCacheDirectory(this);
            String apkName = urlStr.substring(urlStr.lastIndexOf("/") + 1, urlStr.length());
            File apkFile = new File(dir, apkName);
            out = new FileOutputStream(apkFile);
            byte[] buffer = new byte[BUFFER_SIZE];

            int oldProgress = 0;

            while ((byteRead = in.read(buffer)) != -1) {
                byteSum += byteRead;
                out.write(buffer, 0, byteRead);


            }

            installApk(this, apkFile);

            mNotifyManager.cancel(NOTIFICATION_ID);

        } catch (Exception e) {
            Log.e(TAG, "download apk file error:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        extracted();
    }

     /**
      * @description mqtt订阅信息
      * @date: 2024/11/10 12:08
      * @author: mark
      * @param
      * @return
      */
    private void extracted() {
        MqttManager mqtt = new MqttManager();
        mqtt.connectMqtt();
        mqtt.subscribe(mainTopic, new MqttCallback() {

            @Override
            public void connectionLost(Throwable throwable) {

            }


            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                if (topic != null && topic.equals(mainTopic) && message != null){
                    String msg = message.toString();
                    logger.info(msg);

                    Toast.makeText(DownloadService.this,"接收成功",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }
        });
    }


    private void installApk(Context context, File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // for Android 7.0 and newer version, we need to use FileProvider to pass the file path, otherwise it will throw FileUriExposedException
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".update.provider", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(getApkUri(apkFile), "application/vnd.android.package-archive");
        }

        startActivity(intent);
    }


    private Uri getApkUri(File apkFile) {
        Log.d(TAG, apkFile.toString());

        try {
            String[] command = {"chmod", "777", apkFile.toString()};
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri uri = Uri.fromFile(apkFile);
        Log.d(TAG, uri.toString());

        return uri;
    }

    private File getCacheDirectory(Context context) {
        File cacheDir = context.getCacheDir();
        if (cacheDir == null) {
            Log.w(TAG, "Can't define system cache directory!");
        }
        return cacheDir;
    }


    /**
     * @description  上传文件
     * @date: 2024/11/10 11:55
     * @author: mark
     * @param
     * @return
     */
    private void upload(String filePath){
        OkHttpClient client = new OkHttpClient();
        File file = new File(filePath);

        // 请求体
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(
                        "file",
                        file.getName(),
                        MultipartBody.create(MediaType.parse("multipart/form-data"), file)
                ).build();

        // Post 请求
        Request request = new Request.Builder()
                .url("https://www.baidu.com")
                .post(body)
                .build();

        // 执行异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                // 上传完毕
            }
        });
    }
}
